package com.demo.las.service;

import com.demo.las.entity.StudyRecord;
import com.demo.las.repository.StudyRecordRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.List;
import java.util.Optional;

@Service
public class StudyRecordService {

    @Autowired
    private StudyRecordRepository studyRecordRepository;

    @Autowired
    private KnowledgeAssetService knowledgeAssetService;

    public StudyRecord createStudyRecord(StudyRecord studyRecord) {
        // 验证数据
        if (studyRecord.getStudyDate() == null) {
            studyRecord.setStudyDate(LocalDate.now());
        }
        
        // 保存学习记录
        StudyRecord savedRecord = studyRecordRepository.save(studyRecord);
        
        // 更新知识资产
        updateKnowledgeAsset(studyRecord);
        
        return savedRecord;
    }

    public List<StudyRecord> getStudyRecordsByUser(Long userId) {
        return studyRecordRepository.findByUserIdOrderByStudyDateDesc(userId);
    }

    public List<StudyRecord> getStudyRecordsByUserAndSubject(Long userId, String subject) {
        return studyRecordRepository.findByUserIdAndSubjectOrderByStudyDateDesc(userId, subject);
    }

    public List<StudyRecord> getStudyRecordsByDateRange(Long userId, LocalDate startDate, LocalDate endDate) {
        return studyRecordRepository.findByUserIdAndStudyDateBetween(userId, startDate, endDate);
    }

    public Optional<StudyRecord> getStudyRecordById(Long id) {
        return studyRecordRepository.findById(id);
    }

    public StudyRecord updateStudyRecord(StudyRecord studyRecord) {
        return studyRecordRepository.save(studyRecord);
    }

    public void deleteStudyRecord(Long id) {
        studyRecordRepository.deleteById(id);
    }

    public BigDecimal getTotalStudyTime(Long userId, LocalDate startDate, LocalDate endDate) {
        BigDecimal total = studyRecordRepository.getTotalStudyTimeByUserAndDateRange(userId, startDate, endDate);
        return total != null ? total : BigDecimal.ZERO;
    }

    public BigDecimal getTotalStudyTimeBySubject(Long userId, String subject, LocalDate startDate, LocalDate endDate) {
        BigDecimal total = studyRecordRepository.getTotalStudyTimeByUserSubjectAndDateRange(userId, subject, startDate, endDate);
        return total != null ? total : BigDecimal.ZERO;
    }

    public List<Object[]> getStudyTimeBySubject(Long userId, LocalDate startDate, LocalDate endDate) {
        return studyRecordRepository.getStudyTimeBySubject(userId, startDate, endDate);
    }

    public BigDecimal getAverageEfficiency(Long userId, LocalDate startDate, LocalDate endDate) {
        BigDecimal avg = studyRecordRepository.getAverageEfficiencyByUserAndDateRange(userId, startDate, endDate);
        return avg != null ? avg : BigDecimal.ZERO;
    }

    public BigDecimal getAverageQuality(Long userId, LocalDate startDate, LocalDate endDate) {
        BigDecimal avg = studyRecordRepository.getAverageQualityByUserAndDateRange(userId, startDate, endDate);
        return avg != null ? avg : BigDecimal.ZERO;
    }

    public List<Object[]> getDailyStudyTimeTrend(Long userId, LocalDate startDate, LocalDate endDate) {
        return studyRecordRepository.getDailyStudyTimeTrend(userId, startDate, endDate);
    }

    public Long getDistinctSubjectCount(Long userId, LocalDate startDate, LocalDate endDate) {
        return studyRecordRepository.getDistinctSubjectCount(userId, startDate, endDate);
    }

    /**
     * 更新知识资产
     */
    private void updateKnowledgeAsset(StudyRecord studyRecord) {
        knowledgeAssetService.updateAssetFromStudyRecord(
            studyRecord.getUserId(),
            studyRecord.getSubject(),
            studyRecord.getStudyTime(),
            studyRecord.getEfficiencyScore(),
            studyRecord.getQualityScore()
        );
    }

    /**
     * 计算学习效率指数
     */
    public BigDecimal calculateEfficiencyIndex(Long userId, LocalDate startDate, LocalDate endDate) {
        BigDecimal totalTime = getTotalStudyTime(userId, startDate, endDate);
        BigDecimal avgEfficiency = getAverageEfficiency(userId, startDate, endDate);
        BigDecimal avgQuality = getAverageQuality(userId, startDate, endDate);
        
        if (totalTime.compareTo(BigDecimal.ZERO) == 0) {
            return BigDecimal.ZERO;
        }
        
        // 效率指数 = 总时间 × 平均效率 × 平均质量
        return totalTime.multiply(avgEfficiency).multiply(avgQuality);
    }

    /**
     * 获取学习统计摘要
     */
    public StudyStatistics getStudyStatistics(Long userId, LocalDate startDate, LocalDate endDate) {
        StudyStatistics stats = new StudyStatistics();
        stats.setTotalStudyTime(getTotalStudyTime(userId, startDate, endDate));
        stats.setAverageEfficiency(getAverageEfficiency(userId, startDate, endDate));
        stats.setAverageQuality(getAverageQuality(userId, startDate, endDate));
        stats.setSubjectCount(getDistinctSubjectCount(userId, startDate, endDate));
        stats.setEfficiencyIndex(calculateEfficiencyIndex(userId, startDate, endDate));
        
        return stats;
    }

    // 内部类：学习统计摘要
    public static class StudyStatistics {
        private BigDecimal totalStudyTime = BigDecimal.ZERO;
        private BigDecimal averageEfficiency = BigDecimal.ZERO;
        private BigDecimal averageQuality = BigDecimal.ZERO;
        private Long subjectCount = 0L;
        private BigDecimal efficiencyIndex = BigDecimal.ZERO;

        // Getters and Setters
        public BigDecimal getTotalStudyTime() { return totalStudyTime; }
        public void setTotalStudyTime(BigDecimal totalStudyTime) { this.totalStudyTime = totalStudyTime; }
        
        public BigDecimal getAverageEfficiency() { return averageEfficiency; }
        public void setAverageEfficiency(BigDecimal averageEfficiency) { this.averageEfficiency = averageEfficiency; }
        
        public BigDecimal getAverageQuality() { return averageQuality; }
        public void setAverageQuality(BigDecimal averageQuality) { this.averageQuality = averageQuality; }
        
        public Long getSubjectCount() { return subjectCount; }
        public void setSubjectCount(Long subjectCount) { this.subjectCount = subjectCount; }
        
        public BigDecimal getEfficiencyIndex() { return efficiencyIndex; }
        public void setEfficiencyIndex(BigDecimal efficiencyIndex) { this.efficiencyIndex = efficiencyIndex; }
    }
}
